import { useState, useEffect, useMemo } from 'react';
import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import moment from 'moment';
import { InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import Avatar from '../SyncComponents/WapProcessLog/Avatar';
import { getProcessLog } from './service';
import { processState } from '../SyncComponents/WapProcessLog/utils';

export default function Logs(props: any) {
    const { instanceId, setCurrent, setProcessLogData } = props;
    const [logList, setLogList] = useState<any>([]);

    useEffect(() => {
        getProcessLog({ processInstanceId: instanceId }).then((res) => {
            if (res && res.details && res.details.rows && res.details.rows.length > 0) {
                const logs: any[] = [];
                const mutationrows = [];
                const newRows = res.details.rows;
                const i = newRows.length - 1;
                if (newRows[i].taskState != '170') {
                    newRows[i].taskState = '220';
                };
                for (let index = 0; index < newRows.length; index++) {
                    const element = newRows[index];
                    mutationrows.push(element);
                };
                [...mutationrows, {}].reduce((total, current, currentIndex, array) => {
                    if (array[total].task_Def_id != current.task_Def_id) {
                        logs.push(array.slice(total, currentIndex));
                        return currentIndex;
                    } else {
                        return total;
                    }
                }, 0);
                setLogList(logs);
                setProcessLogData(res.details.rows);
            }
        });
    }, []);

    const reverseList = () => {
        const _logList = [...logList.reverse()];
        setLogList(_logList);
    };

    const onClickContent = (e: any) => {
        if (e?.target?.classList?.value == 'process-log-logs-content') {
            setCurrent({});
        };
    };

    return (
        <div className='process-log-logs'>
            <div className='process-log-logs-sort' onClick={reverseList}>
                <InbizIcon
                    type='icon-paixu'
                    style={{
                        color: '#ddd',
                        fontSize: 20,
                    }}
                />
            </div>
            <div className='process-log-logs-content' onClick={onClickContent}>
                {
                    logList?.map((item: any) => {
                        return (
                            <LogsItem key={item?.id} data={item} {...props} />
                        )
                    })
                }
            </div>
        </div>
    )
};

function LogsItem(props: any) {
    const { data, current, setCurrent } = props;
    const [isExpanded, setIsExpanded] = useState(true);

    const getStateName = (data: any[]) => {
        let index = 0;
        if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '170') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '170');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '220') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '220');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '10') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '10');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '50') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '50');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '130') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '130');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '0') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '0');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '5') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '5');
        } else if (data.findIndex((ele: { taskState: string; }) => ele.taskState == '20') > -1) {
            index = data.findIndex((ele: { taskState: string; }) => ele.taskState == '20');
        }
        return index;
    };

    const toggleIsExpanded = (e: any) => {
        e.stopPropagation();
        setIsExpanded(!isExpanded);
    };

    return (
        <div className={`process-log-logs-content-item ${current?.id == data?.[0]?.id ? 'selected' : ''}`} onClick={() => { setCurrent(data?.[0]) }}>
            <div className='process-log-logs-content-item-header'>
                <div>
                    <InbizIcon
                        type={
                            processState[data[getStateName(data)].taskState]
                                ? processState[data[getStateName(data)].taskState].secondName ==
                                    'ProcessLog.refuse'
                                    ? 'icon-yiwancheng'
                                    : processState[data[getStateName(data)].taskState].stateIcon
                                : 'icon-close_filled'
                        }
                        style={{ fontSize: 22, color: 'orange', transition: '0.3s' }}
                    />
                    <div className='process-log-logs-content-item-header-userTask'>{data[0].name}</div>
                    <div
                        className='process-log-logs-content-item-header-step'
                        style={{
                            color: processState[data[getStateName(data)].taskState]
                                ? processState[data[getStateName(data)].taskState].secondName ==
                                    'ProcessLog.refuse'
                                    ? '#71b771'
                                    : processState[data[getStateName(data)].taskState].stateColor
                                : 'orange',
                        }}
                    >
                        {processState[data[getStateName(data)].taskState] ? (
                            processState[data[getStateName(data)].taskState].secondName ==
                                'ProcessLog.refuse' ? (
                                <TextWidget>ProcessLog.approved</TextWidget>
                            ) : (
                                <TextWidget>
                                    {processState[data[getStateName(data)].taskState].secondName}
                                </TextWidget>
                            )
                        ) : (
                            data[getStateName(data)].taskState
                        )}
                    </div>
                </div>
                {
                    isExpanded
                        ?
                        <CaretDownOutlined className='process-log-logs-content-item-header-icon' onClick={(e) => { toggleIsExpanded(e) }} />
                        :
                        <CaretRightOutlined className='process-log-logs-content-item-header-icon' onClick={(e) => { toggleIsExpanded(e) }} />
                }
            </div>
            <div className='process-log-logs-content-item-body' style={{ height: isExpanded ? 'auto' : 0 }}>
                {data.map((user: any, i: number) => (
                    <>
                        <div className='process-log-logs-content-item-body-item'>
                            <div className='process-log-logs-content-item-body-item-user'>
                                <UserImg userId={user.userIdentityID} />
                                <div className='process-log-logs-content-item-body-item-userName' title={user.assigneeName}>
                                    {user.assigneeName}
                                </div>
                            </div>
                            {user.taskState != '0' ? (
                                <div className='process-log-logs-content-item-body-item-other'>
                                    {processState[user.taskState] ? (
                                        user.taskState == '50' ? (
                                            <TextWidget>ProcessLog.beenassigned</TextWidget>
                                        ) : user?.taskState == '150' &&
                                            user?.task_Def_id?.indexOf('ctSign-') > -1 ? (
                                            <TextWidget>ProcessLog.plusSignComplete</TextWidget>
                                        ) : (
                                            (data?.length == 1 && user?.taskState == '1') ? <TextWidget>ProcessLog.agree</TextWidget> :
                                                (data?.some((item4: any) => item4?.taskState == '5') && user?.taskState != '5') ?
                                                    <TextWidget>ProcessLog.autom</TextWidget> :
                                                    <TextWidget>{processState[user.taskState].stateName}</TextWidget>
                                        )
                                    ) : (
                                        getMessage('ProcessLog.noStatus')
                                    )}
                                    {user.taskState == '50' ? ' ' : ' : '}
                                    {user.taskState == '50'
                                        ? ''
                                        : user.endTime
                                            ? moment(user.endTime).format('YYYY/MM/DD HH:mm')
                                            : processState[user?.taskState]?.secondName ==
                                                'ProcessLog.approvaling'
                                                ? ''
                                                : moment(user.startTime).format('YYYY/MM/DD HH:mm')}
                                </div>
                            ) : (
                                <div className='process-log-logs-content-item-body-item-other'>
                                    <TextWidget>ProcessLog.approvaling</TextWidget>
                                </div>
                            )}
                        </div>
                        {user.taskOwnerName && user.assigneeName && (
                            <div className='process-log-logs-content-item-body-item'>
                                <div className='process-log-logs-content-item-body-item-user'>
                                    <UserImg userId={user.ownUserID} />
                                    <div className='process-log-logs-content-item-body-item-userName' title={user.taskOwnerName}>
                                        {' '}
                                        {user.taskOwnerName}
                                    </div>
                                </div>
                                {user.taskState != '0' && (
                                    <div style={{ fontSize: 12, color: '#707070' }}>
                                        {processState[user.taskState] ? (
                                            <TextWidget>{processState['50'].stateName}</TextWidget>
                                        ) : (
                                            getMessage('ProcessLog.noStatus')
                                        )}
                                        {user.taskState == '50' ? ' ' : ': '}
                                        {user.taskState == '50'
                                            ? ''
                                            : user.endTime
                                                ? moment(user.endTime).format('YYYY/MM/DD HH:mm')
                                                : processState[user?.taskState]?.secondName ==
                                                    'ProcessLog.approvaling'
                                                    ? ''
                                                    : moment(user.startTime).format('YYYY/MM/DD HH:mm')}
                                    </div>
                                )}
                            </div>
                        )}
                        {user.taskOwnerName && user.assigneeName && (
                            <div className='process-log-logs-content-item-body-item-body'>
                                <div className='process-log-logs-content-item-body-item-body-commentText' title={user.comment}>
                                    {user.taskOwnerName} <TextWidget>ProcessLog.assignto</TextWidget>{' '}
                                    {user.assigneeName}
                                </div>
                            </div>
                        )}
                        {user.ccMember && (
                            <div className='process-log-logs-content-item-body-item-body'>
                                <div style={{ margin: '5px 0' }}>
                                    <TextWidget>ProcessLog.ccMember</TextWidget>:
                                </div>
                                <div className='process-log-logs-content-item-body-item-body-commentText' title={user.ccMember}>
                                    {user.ccMember}
                                </div>
                            </div>
                        )}
                    </>
                ))}
            </div>
        </div>
    )
}

const UserImg = (props: { userId: string }) => {
    return useMemo(() => {
        return props?.userId ? (
            <Avatar
                style={{ width: 32, height: 32, marginLeft: 16, marginRight: 10, borderRadius: 16 }}
                userId={props?.userId}
            />
        ) : (
            <InbizIcon
                type="icon-process-defaultAvatar"
                style={{ fontSize: 30, marginLeft: 16, marginRight: 10, borderRadius: 4 }}
            />
        );
    }, [props?.userId]);
};
